package com.hopes.bizz.protocol.hj212.config;

import com.hopes.bizz.protocol.hj212.server.ServerInitHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author jie.dai
 */
@Component
@Slf4j
public class Hj212Server {
    private NioEventLoopGroup parentGroup;
    private NioEventLoopGroup workerGroup;
    @Value("${hj212.port:2023}")
    private Integer port;
    @Value("${hj212.worker:8}")
    private Integer workerThread;
    @Value("${hj212.charSize:8096}")
    private Integer charSize;

    @Autowired
    private ServerInitHandler dataTransferInitHandler;

    @PostConstruct
    private void init() {
        log.info("begin 启动中心服务数据监听******");
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        parentGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup(workerThread);

        serverBootstrap.group(parentGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(dataTransferInitHandler)
                .bind(port);
        log.info("[success] 中心服务监听端口 port:{}", port);
        log.info("end 启动中心服务数据监听******");
    }

    @PreDestroy
    private void destroy() {
        if (parentGroup != null) {
            try {
                parentGroup.shutdownGracefully().sync();
                workerGroup.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                log.error("数据接受服务停止失败", e);
            }
        }
    }
}
